<script setup>
import { ref, watch, nextTick } from 'vue';
import WelcomeMessage from '@/components/WelcomeMessage.vue';
const props = defineProps({
  messages: {
    type: Array,
  }
});
const messagesContainer = ref(null);
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

watch(() => props.messages, () => {
  scrollToBottom();
}, { deep: true });
</script>

<template>
  <div class="messages-container" ref="messagesContainer">
    <template v-if="props.messages.length === 0">
      <WelcomeMessage />
    </template>
    <template v-else>
      <div v-for="(msg, idx) in props.messages" :key="idx" :class="['bubble', msg.role]">
        <template v-if="msg.files && msg.files.length">
          <div class="bubble-files">
            <div v-for="(file, fidx) in msg.files" :key="fidx" class="bubble-file">
              <i class="fas fa-paperclip"></i> {{ file.name }}
            </div>
          </div>
        </template>
        <div v-if="msg.loading && msg.role === 'assistant'" class="bubble-content">
          <i class="fas fa-spinner fa-spin"></i> 正在思考...
        </div>
        <div v-else class="bubble-content" style="white-space: pre-line;">
          <!-- 支持换行显示 -->
          {{ msg.displayedContent }}
        </div>
      </div>
    </template>
  </div>
</template>

<style scoped>
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: var(--bgcolor);
}

.bubble {
  max-width: 70%;
  margin-bottom: 18px;
  padding: 14px 18px;
  border-radius: 16px;
  background: #f1f5f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  word-break: break-all;
  position: relative;
}

.bubble.user {
  background: #4895ef;
  color: #fff;
  margin-left: auto;
}

.bubble.assistant {
  background: #f1f5f9;
  color: #222;
  margin-right: auto;
}

.bubble-files {
  margin-bottom: 8px;
}

.bubble-file {
  background: #e0e7ef;
  border-radius: 8px;
  padding: 6px 12px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
  color: #2563eb;
}

.bubble-content {
  font-size: 15px;
  line-height: 1.7;
}
</style>